#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/watchdog.h>
#include "z_logger.h"

static int wd_fd = -1;

void wd_open(const char *filename) {
    const char *dev_name = filename ? filename : "/dev/watchdog";

    close(wd_fd);
    wd_fd = open(dev_name, O_WRONLY);
    if (wd_fd < 0) {
        log_error("failed to open `%s`", dev_name);
    }
}

void wd_close(const char *cmdline) {
    close(wd_fd);

    if (cmdline) {
        if (system(cmdline) < 0) {
            log_warn("failed to recovery default watchdog `%s`", cmdline);
        }
    }
}

void wd_set_timeout(int timeout) {
    if (wd_fd >= 0) {
        log_info("timeout=%d", timeout);
        ioctl(wd_fd, WDIOC_SETTIMEOUT, &timeout);
    }
}

void wd_tick() {
    if (wd_fd >= 0) {
        char food = 0;
        write(wd_fd, &food, 1);
    }
}
